<template>
  <view class="container">
    <view class="input-group">
      <view class="input-row">
        <text>新密码</text>
        <input type="password" v-model="newPassword" placeholder="请输入6-12位数字+字母的新密码" />
      </view>
      <view class="input-row">
        <text>确认新密码</text>
        <input type="password" v-model="confirmPassword" placeholder="请再次输入新密码" />
      </view>
    </view>
    <view class="button-group">
      <button @click="cancel">取消</button>
      <button @click="changePassword">确定修改密码</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      newPassword: '',
      confirmPassword: '',
     
      userInfo: {
        psy_id: 1, // 这里是当前用户的ID，需要从后端或其他地方获取
        psy_password:'',
      },
    };
  },
  methods: {
    cancel() {
      uni.navigateTo({
        url: '/pages/psy/my/profile' 
      });
    },
    validatePassword(password) {
      // 验证密码是否为6-12字符且包含数字和字母
      const regex = /(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,12}$/;
      return regex.test(password);
    },
    async changePassword() {
      if (!this.validatePassword(this.newPassword)) {
        uni.showToast({ title: '新密码必须是6-12位数字+字母', icon: 'none' });
        return;
      }
      if (this.newPassword !== this.confirmPassword) {
        uni.showToast({ title: '两次输入的新密码不一致', icon: 'none' });
        return;
      }
      
      this.userInfo.psy_password=this.newPassword;

      try {
        const response = await uni.request({
          url: `http://127.0.0.1:5001/api_1_0/psyConsultant/${this.userInfo.psy_id}`, 
          method: 'PUT',
          data: {
            psy_password:this.userInfo.psy_password
          },
          header: {
            'Content-Type': 'application/json'
          }
        });

        if (response.data.code === '2000') {
          uni.navigateTo({
            url: '/pages/psy/my/profile' 
          });
        } else {
          // 显示后端返回的错误信息
          uni.showToast({ title: response.data.message || '密码修改失败', icon: 'none',duration:2000});
        }
      } catch (error) {
        uni.showToast({ title: '请求出错，请稍后重试', icon: 'none' });
        console.error('请求出错:', error);
      }
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
}

.input-group {
  margin-bottom: 40px;
}

.input-row {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.input-row text {
  width: 80px;
}

.input-row input {
  flex: 1;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
}

.button-group {
  display: flex;
  justify-content: space-between;
}

button {
  width: 45%;
  padding: 10px;
  background-color: #81b337;
  color: white;
  border: none;
  border-radius: 5px;
}

button:first-child {
  background-color: #f1f1f1;
  color: black;
}
</style>